from moviepy.editor import *
import re
import json
import random
import uuid
# with open('gifs.json','r',encoding='utf8') as gj:
with open('gifs_22.json','r',encoding='utf8') as gj:
    # videosJson = json.load(videosJson)
    gifJson = json.load(gj)

gif_list = gifJson

def randomGifs():
    # print("randomVideos")
    return random.choice(gif_list)["url"]

# 获取音频(音轨)相关信息dict
def getAudio(url):
    # print("getAudio")
    audio_clip = VideoFileClip(url)
    return {
        'duration': audio_clip.duration,
        'clip': audio_clip.audio
    }


# 根据时长获取素材信息list
def getVideoByDuration(duration):
    # 视频信息数组
    clip_data_list = []
    clip_list = []
    # 初始化开始时间
    video_start = 0
    while(video_start < duration):
        # 视频片段url(str)
        print(f"进度{video_start}/{duration}")
        clip_url = randomGifs()
        # 片段文件
        clip = VideoFileClip(clip_url)
        clip_list.append(clip.set_start(video_start).set_pos(("center","center")))
        clip_data_list.append({
            'video_start': video_start,
            'clip_url': clip_url
        })
        video_start = video_start + clip.duration
    # 保存素材列表
    print(clip_data_list)
    # saveData(clip_data_list)
    # return clip_data_list, clip_list
    return CompositeVideoClip(clip_list, size=(848, 480))


# 分段拼接
def splicingEvery(audio_video):
    duration = audio_video.duration
    if duration > 300:
        audio_video1 = audio_video.subclip(0, duration / 2)
        splicingEvery(audio_video1)
        audio_video2 = audio_video.subclip(duration / 2, duration)
        splicingEvery(audio_video2)
    else:
        clip = getVideoByDuration(duration)
        writeVideo(clip.set_audio(audio_video.audio))


# 根据音频地址提取音频
def getVideoByAudio(audio_url):
    # splicingEvery(AudioFileClip(audio_url))
    splicingEvery(VideoFileClip(audio_url))

# 添加音轨且输出视频
def addAudio(audio, clip):
    # print("addAudio")
    # 加音轨
    writeVideo(clip.set_audio(audio))

def writeVideo(clip):
    video_name = f"{uuid.uuid1()}.mp4"
    # print("writeVideo")
    # 保存视频信息
    # video_name = "final_clip.mp4"
    # saveData({'name': video_name, 'value': clip_data_list})
    # 输出视频
    clip.write_videofile(video_name)
    
def main():
    # print("main")
    # 片头
    # top_url = 'srt/top.mp4'
    # top_video = VideoFileClip(top_url)
    # 音频转视频
    getVideoByAudio('E:/pybase/gitbase/videoUtils/audio.mp4')
    
def test(duration):
    # print(gifJson[0])
    clip = getVideoByDuration(duration)
    writeVideo(clip)
    # VideoFileClip(randomVideos()).write_videofile("final.mp4")
#
# main()是根据90行的文件为音轨，当前音轨文件是视频文件，如果是纯音频，须将67、68行注释换一下#
# test()方法可以直接输出没有音轨的视频()里需要加入视频时长
# #
if __name__ == '__main__':
    # main()
    # for i in range(4):
        test(random.randint(60, 200))
    